package com.bw.shop_2302.update

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bw.base.entity.Res
import com.bw.base.entity.Res2
import com.bw.base.entity.SendCodeEntity
import com.bw.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class UpdateViewModel:BaseViewModel() {

    val sendsuccess=MutableLiveData<Res<SendCodeEntity>>()
    var sendfail=MutableLiveData<String>()

    fun sendcode(phone:String){
        //在作用域中调用挂起函数,自己添加try-catch 防止有异常情况时项目崩溃
        viewModelScope.launch {
            try {

                //直接调用Api中的
                sendsuccess.value = apiServer.SendCode(phone)

            }catch (e:Exception){
                sendfail.value=e.message
            }

        }
    }

    var updatesuccess=MutableLiveData<Res2>()
    var updatefail=MutableLiveData<String>()

    fun update(account:String,captcha:String,password:String){

        viewModelScope.launch {

            try {

                var map= mutableMapOf<String,Any>()
                map["account"]=account
                map["captcha"]=captcha
                map["password"]=password
                val toJson = Gson().toJson(map)

                val create = RequestBody.create("application/json;charset=utf-8".toMediaType(), toJson)

                updatesuccess.value=apiServer.Update(create)

            }catch (e:Exception){
                updatefail.value=e.message
            }
        }



    }
}